package com.ls.lsqc.modules.sys.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lsqc.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lsqc.common.config.Global;
import com.ls.lsqc.common.persistence.AjaxDone;
import com.ls.lsqc.common.persistence.BaseEntity;
import com.ls.lsqc.common.persistence.Page;
import com.ls.lsqc.common.utils.StringUtils;
import com.ls.lsqc.common.web.BaseController;
import com.ls.lsqc.modules.sys.entity.Role;
import com.ls.lsqc.modules.sys.service.SystemService;

import freemarker.template.Configuration;

/**
 * 角色Controller
 * @author LiuPeng
 * @version 2016-10-13
 */
@Controller
@RequestMapping(value = "${adminPath}/database/role/")
public class RoleController extends BaseController {

	@Autowired
	private SystemService systemService;
	@Autowired
	Configuration freemarkerConfiguration;
	
	/**
	  * @Title: get
	  * @Description: 获取角色信息
	  * @param @param id
	  * @param @param request
	  * @param @return
	  * @return Role 
	  * @throws
	  */
	
	@ModelAttribute("role")
    public Role get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
        if (StringUtils.isNotBlank(id)){
        	
        	// 执行查询语句 查询基本信息
            return systemService.getRole(Long.parseLong(id));
        }else{
        	
        	// 若为空，实例化
            return new Role();
        }
    }
	/**
	  * @Title: list
	  * @Description: 进入一览页面
	  * @param @param role
	  * @param @param request
	  * @param @param response
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("database:role:view")
	@RequestMapping(value = {"list", ""})
	public String list(Role role, HttpServletRequest request, HttpServletResponse response,Model model) {
		
		// 查询一览页面数据
		//Page<Role> page = systemService.findRole(new Page<Role>(request, response), role);
		
		// 将page值赋值给mvc model层返回jsp页面
		//model.addAttribute("page", page);
		
		// 返回页面地址
		return "modules/sys/roleList";
	}
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param role
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("database:role:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Role role, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "role");
		// 画面取得的检索项目
		// 角色名称
		String roleName = role.getRoleName();
		
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&roleName=");
		searchParam.append(roleName);
		
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		// 查询一览页面数据
		Page<Role> page = systemService.findRole(new Page<Role>(request, response), role);
						
		// 读取系统路径
		// 读取文件生成字符串
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		String[] values = null;
		//Message信息
		map.put("roleScope1", SystemMessageUtils.getMessageName ("role_dataField1"));
		map.put("roleScope2", SystemMessageUtils.getMessageName ("role_dataField2"));
		map.put("roleScope3", SystemMessageUtils.getMessageName ("role_dataField3"));
		map.put("roleScope4", SystemMessageUtils.getMessageName ("role_dataField4"));
		map.put("roleScope5", SystemMessageUtils.getMessageName ("role_dataField5"));
		map.put("roleScope6", SystemMessageUtils.getMessageName ("role_dataField6"));
		map.put("roleSys1", SystemMessageUtils.getMessageName ("role_no"));
		map.put("roleSys2", SystemMessageUtils.getMessageName ("role_yes"));
		
		map.put("adminUri", strUri);
		map.put("Roles", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("roleList.ftl"), map);
		listMap.put("role", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
    /**
      * @Title: show
      * @Description: 查看页面
      * @param @param role
      * @param @param model
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("database:role:view")
    @RequestMapping(value = "show")
    public String show(Role role, Model model) {
    	
    	// 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("role", role);
        model.addAttribute("menuList", systemService.findAllMenu());
        // 返回页面地址
        return "modules/sys/roleShow";
    }

	/**
	  * @Title: form
	  * @Description: 新建 编辑页面
	  * @param @param role
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("database:role:view")
	@RequestMapping(value = "form")
	public String form(Role role, Model model) {
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("role", role);
		model.addAttribute("menuList", systemService.findAllMenu());
		
		// 返回页面地址
		return "modules/sys/roleEdit";
	}


	/**
	  * @Title: checkName
	  * @Description: 查重
	  * @param @param id
	  * @param @param roleName
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("database:role:edit")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String oldRoleName, String roleName) {
		
        try {
        	// 页面获取数据值与旧数据若相同，并且数据值不为null
            if (roleName != null && roleName.toUpperCase().equals(oldRoleName.toUpperCase())) {
            	// 返回true
                return "true";
            // 页面获取数据值与旧数据若不相同，查询结果为null，并且数据值不为null
            } else if (roleName != null&& systemService.getRoleByName(roleName) == null) {
            	// 返回true
            	return "true";
            }
            // 数据值重名
            return "false";

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        }
        // 数据值重名
        return "false";
	}
	

	/**
	  * @Title: save
	  * @Description: 保存 更新
	  * @param @param role
	  * @param @param request
	  * @param @param model
	  * @param @param response
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("database:role:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Role role, HttpServletRequest request, Model model, HttpServletResponse response ) {
		// 判断id是否为null （判断新建或修改）
		if(role.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			Role roleNew=get(role.getId().toString());
			
			// 判断数据是否删除
	        if(roleNew==null || BaseEntity.DEL_FLAG_DELETE.equals(roleNew.getDeleteFlag())){
	        	// 返回提示信息
	        	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	        }
	        // 排他处理
		    if(role.getVersion()==get(role.getId().toString()).getVersion()){
		    	// 版本号加1
		    	role.setVersion(role.getVersion()+1);
		    }else{
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}else{
			// 新建版本号赋值1
			role.setVersion(1L);
		}
		
		try {
			// 若启用未选择赋值1
			if(role.getEnableFlag()==null){
				role.setEnableFlag("1");
			}
			
		    // 保存角色信息
			systemService.saveRole(role);
		
			// 保存成功返回提示信息
	        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName ("roleSaveSuccess")));
	
		 } catch (Exception e) {
	           // 记录日志
	           logger.error(e.getMessage(), e);
			// 提示错误信息
            return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
	     }
	}

	/**
      * @Title: delete
      * @Description: 删除
      * @param @param role
      * @param @param response
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("database:role:edit")
	@RequestMapping(value = "delete")
	public String delete(Role role, HttpServletResponse response) {
		
		    try {
		    	// 执行逻辑删除方法
		    	systemService.deleteRole(role);
            } catch (Exception e) {
                // 记录日志
                logger.error(e.getMessage(), e);
            	// 提示错误信息
                return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
            }
		     // 提示删除成功信息
			return renderString(response,AjaxDone.ok(getText("role_delete_success")));
    }
}
